// eslint-disable-next-line import/no-extraneous-dependencies
const Client = require('ssh2-sftp-client');
// eslint-disable-next-line import/no-extraneous-dependencies
const { run } = require('runjs');
const inquirer = require('inquirer'); //8.2.0
const {
  qiniuConfig: { prefix }, serverConfig, serverConfig: { remoteDist }, localConfig: { sourceSrc },
} = require('./config');

const rawArgv = process.argv.slice(2);
const args = rawArgv.join(' ');

const client = new Client();

/**
 * 手动输入服务器密码
 */
 async function inputPwd() {
  const data = await inquirer.prompt([
    {
      type: "password",
      name: "password",
      message: "服务器密码",
    },
  ]);
  return data.password;
}

/**
 * 手动输入服务器账号 
 */
async function inputUnm() {
  const data = await inquirer.prompt([
    {
      type: "username",
      name: "username",
      message: "服务器账号",
    },
  ]);
  return data.username;
}

const config = { ...serverConfig };

(async () => {

  if (!config.username) {
    config.username = await inputUnm();
  }
  if (!config.password) {
    config.password = await inputPwd();
  }

  await run(`cross-env prefix=${prefix}  vue-cli-service build ${args}`);
  try {
    await client.connect(config);
    client.on('upload', (info) => {
      console.log(`Uploaded：${info.source}`);
    });
    const result = await client.uploadDir(sourceSrc, remoteDist);
    await run('node deploy/upQiniu.js');
    console.log(result);
  } catch (error) {
    console.error(error);
  } finally {
    client.end();
  }
})();
